#include "onlinesortiment.h"
#include "ui_onlinesortiment.h"

OnlineSortiment::OnlineSortiment(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OnlineSortiment)
{
    ui->setupUi(this);
    ui->sortiment_tableWidget->setColumnWidth(0, 60);
    ui->sortiment_tableWidget->setColumnWidth(1, 60);
    ui->sortiment_tableWidget->setColumnWidth(2, 300);
    ui->sortiment_tableWidget->setColumnWidth(3, 40);
    ui->sortiment_tableWidget->setColumnWidth(4, 150);

    db = QSqlDatabase::database();

    loadSortiment();
    ui->sortiment_tableWidget->sortByColumn(2, Qt::AscendingOrder);

    refresh_progress_label = new QLabel();
    refresh_progress_bar = new QProgressBar();

    oc = Rt::oc;
    ui->refresh_pushButton->setEnabled( oc->isLogedIn() );
    QSettings settings("FHsoft", "RemiTool");
    if ( oc->isLogedIn() && settings.value("online/lastSortimentUpdate", QDate()).toDate() < QDate::currentDate() )
        on_refresh_pushButton_clicked();

    connect(oc, SIGNAL(login_success()), this, SLOT(isLogedIn()));
}

OnlineSortiment::~OnlineSortiment()
{
    delete ui;
}

void OnlineSortiment::isLogedIn()
{
    ui->refresh_pushButton->setEnabled(true);
    QSettings settings("FHsoft", "RemiTool");
    if ( settings.value("online/lastSortimentUpdate", QDate()).toDate() < QDate::currentDate() )
        on_refresh_pushButton_clicked();
}

void OnlineSortiment::loadSortiment()
{
    if ( db.isOpen() || db.open() )
    {
        ui->sortiment_tableWidget->setSortingEnabled(false);
        ui->sortiment_tableWidget->clearContents();
        ui->sortiment_tableWidget->setRowCount(0);
        QSqlQuery q(db);
        q.exec("SELECT objektnr, vdznr, titel, og_id, og_bezeichnung FROM online_sortiment;");
        while ( q.next() )
        {
            int row = ui->sortiment_tableWidget->rowCount();
            ui->sortiment_tableWidget->insertRow( row );
            for ( int i=0; i<5; i++ )
            {
                QTableWidgetItem *item = new QTableWidgetItem(q.value(i).toString());
                item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable);
                ui->sortiment_tableWidget->setItem( row, i, item );
            }
        }
        ui->sortiment_tableWidget->setSortingEnabled(true);
    }
}

void OnlineSortiment::on_refresh_pushButton_clicked()
{
    disconnect(oc, SIGNAL(login_success()), this, SLOT(on_refresh_pushButton_clicked()));
    ui->refresh_pushButton->setEnabled(false);

    if ( !oc->isLogedIn() )
    {
        connect(oc, SIGNAL(login_success()), this, SLOT(on_refresh_pushButton_clicked()));
        oc->login();
        return;
    }

    refresh_progress_label->setText(tr("Lade Online Sortiment ..."));
    refresh_progress_bar->setRange(0,0);
    refresh_progress_bar->setTextVisible(false);
    refresh_progress_bar->setFixedWidth(100);
    Rt::statusbar->addPermanentWidget(refresh_progress_label);
    Rt::statusbar->addPermanentWidget(refresh_progress_bar);
    refresh_progress_label->show();
    refresh_progress_bar->show();


    QNetworkRequest r(QUrl("http://www.leverdy.de/kdn_information_sortiment.php?s=2&all=ja"));
    refreshReply = oc->getManager()->get(r);
    connect(refreshReply, SIGNAL(finished()), this, SLOT(refreshReplyFinished()));
}

void OnlineSortiment::refreshReplyFinished()
{
    disconnect(refreshReply, SIGNAL(finished()), this, SLOT(refreshReplyFinished()));
    Rt::statusbar->removeWidget(refresh_progress_label);
    Rt::statusbar->removeWidget(refresh_progress_bar);

    if (refreshReply->error() != QNetworkReply::NoError){
        QMessageBox::warning(this, tr("Online Verbindung"), refreshReply->errorString());
        return;
    }

    QWebPage page;
    page.currentFrame()->setHtml( QString::fromLatin1(refreshReply->readAll()) );

    QTableWidget *tw = new QTableWidget();
    QWebElementCollection dom_tr_collection = page.currentFrame()->findFirstElement("table[class=\"tabellenueberschrift\"]").nextSibling().findAll("tr");

    QProgressDialog *pd = new QProgressDialog(tr("Bitte warten, während das Sortiment aktualisiert wird..."), tr("Abbrechen"), 0, dom_tr_collection.count()*2);
    pd->setMinimumDuration(1000);
    pd->setValue(0);

    QWebElement dom_tr = page.currentFrame()->findFirstElement("table[class=\"tabellenueberschrift\"]").nextSibling().findFirst("tr");
    tw->setColumnCount(9);
    while ( !dom_tr.isNull() )
    {
        tw->insertRow(tw->rowCount());
        QWebElement td = dom_tr.firstChild();
        int i = 0;
        while ( !td.isNull() )
        {
            tw->setItem( tw->rowCount()-1, i++, new QTableWidgetItem( td.toPlainText() ) );
            td = td.nextSibling();
        }
        dom_tr = dom_tr.nextSibling();
        pd->setValue(pd->value()+1);
    }

    if ( db.isOpen() || db.open() )
    {
        db.transaction();
        QSqlQuery q(db);
        for ( int row=0; row < tw->rowCount(); row++ )
        {
            q.prepare("SELECT vdznr, titel, og_id, og_bezeichnung FROM online_sortiment WHERE objektnr = :objektnr;");
            q.bindValue(":objektnr", tw->item(row, 3)->text());
            q.exec();
            if ( !q.first() )
                q.prepare("INSERT INTO online_sortiment ( objektnr, vdznr, titel, og_id, og_bezeichnung ) VALUES ( :objectnr, :vdznr, :titel, :og_id, :og_bezeichnung );");
            else
                q.prepare("UPDATE online_sortiment SET vdznr = :vdznr, titel = :titel, og_id = :og_id, og_bezeichnung = :og_bezeichnung WHERE objektnr = :objektnr;");

            q.bindValue(":objektnr", tw->item(row, 3)->text().simplified());
            q.bindValue(":vdznr", tw->item(row, 5)->text().simplified());
            q.bindValue(":titel", tw->item(row, 2)->text().simplified());
            q.bindValue(":og_id", tw->item(row, 0)->text().simplified());
            q.bindValue(":og_bezeichnung", tw->item(row, 1)->text().simplified());
            q.exec();
            pd->setValue(pd->value()+1);
            if ( pd->wasCanceled() )
                break;
        }
        db.commit();
    }

    loadSortiment();
    Rt::statusbar->showMessage(tr("Online Sortiment erfolgreich aktualisisert"), 5000);
    ui->refresh_pushButton->setEnabled(true);


    QSettings settings("FHsoft", "RemiTool");
    settings.setValue("online/lastSortimentUpdate", QDate::currentDate());
}
